package com.koron.css2.systemManage.service;

import com.github.pagehelper.PageInfo;
import com.google.common.base.Objects;
import com.koron.common.bean.query.OperationQueryBean;
import com.koron.css2.ApplicationConfig;
import com.koron.css2.common.utils.HttpUtils;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.css2.serviceManage.utils.RedisUtils;
import com.koron.css2.systemManage.bean.OperateBean;
import com.koron.css2.systemManage.bean.OperationTreeBean;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 操作业务处理类
 * @author 周利斌
 *
 */
@Service
public class OperationService implements IOperationService{
	
	private static Logger log = LogManager.getLogger(OperationService.class);
	
	public void addOperation(OperateBean operation) {
		if(StringUtils.isEmpty(operation.getOpName())) {
			throw new IllegalArgumentException("opName 不能为空");
		}
		if(StringUtils.isEmpty(operation.getForeignkey())) {
			operation.setForeignkey("all");
		}
		if(operation.getOpWeight() == null) {
			operation.setOpWeight(1024);
		}
		RedisUtils.del("alloperation");
		operation.setOpStatus(1);
		operation.setTenantCode(ApplicationConfig.getAuthorityTenantCode());
		String url = ApplicationConfig.getAuthorityUrl() + ApplicationConfig.ADD_OPERATE_URL;
		String result = HttpUtils.sendPostJson(url, JsonUtils.objectToJson(operation));
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("添加操作失败,"+json.getString("description"));
		}
	}
	
	public void addOrgOperation(String app, String orgCode, List<String> operationCodes) {
		if(StringUtils.isEmpty(app)) {
			throw new IllegalArgumentException("app 不能为空");
		}
		if(StringUtils.isEmpty(orgCode)) {
			throw new IllegalArgumentException("orgCode 不能为空");
		}
		if(operationCodes ==null || operationCodes.size() == 0) {
			throw new IllegalArgumentException("operationCodes 不能为空");
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("orgCode", orgCode);
		param.put("operationCodeList", operationCodes);
		param.put("tenantCode", ApplicationConfig.getAuthorityTenantCode());
		RedisUtils.del(orgCode + "_alloperation");
		String url = ApplicationConfig.getAuthorityUrl() + "/permissionController/addOrgOperate.htm";
		String result = HttpUtils.sendPostJson(url, JsonUtils.objectToJson(param));
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("添加操作失败");
		}
	}

	public void addOrgOperation(String app, List<String> orgCodeList, List<String> operationCodeList){
		if(StringUtils.isEmpty(app)) {
			throw new IllegalArgumentException("app 不能为空");
		}
		if(operationCodeList == null || operationCodeList.size() == 0) {
			throw new IllegalArgumentException("operationCodeList 不能为空");
		}
		if(orgCodeList == null || orgCodeList.size() == 0) {
			throw new IllegalArgumentException("orgCodeList 不能为空");
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("orgCode", orgCodeList);
		param.put("operationCodeList", operationCodeList);
		param.put("tenantCode", ApplicationConfig.getAuthorityTenantCode());
		for (String orgCode : orgCodeList){
			RedisUtils.del(orgCode + "_alloperation");
		}
		String url = ApplicationConfig.getAuthorityUrl() + "/permissionController/batchAddOrgOperate.htm";
		String result = HttpUtils.sendPostJson(url, JsonUtils.objectToJson(param));
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("添加操作失败");
		}
	}
	
	public void updateOperation(OperateBean operation) {
		if(StringUtils.isEmpty(operation.getOpName())) {
			throw new IllegalArgumentException("opName 不能为空");
		}
		RedisUtils.del("alloperation");
		operation.setTenantCode(ApplicationConfig.getAuthorityTenantCode());
		String url = ApplicationConfig.getAuthorityUrl() + ApplicationConfig.UPDATE_OPERATE_URL;
		String result = HttpUtils.sendPostJson(url, JsonUtils.objectToJson(operation));
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("修改操作失败");
		}
	}
	
	public void deleteOperation(List<String> opCodeList) {
		if(opCodeList == null) {
			throw new IllegalArgumentException("opCodeList 不能为空");
		}
		RedisUtils.del("alloperation");
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("tenantCode", ApplicationConfig.getAuthorityTenantCode());
		param.put("opCodeList", opCodeList);
		String url = ApplicationConfig.getAuthorityUrl() + ApplicationConfig.DELETE_OPERATE_URL;
		String result = HttpUtils.sendPostJson(url, JsonUtils.objectToJson(param));
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("删除操作失败");
		}
	}
	
	public void addRoleOperation(String roleCode, List<String> opCodeList) {
		if(StringUtils.isEmpty(roleCode)) {
			throw new IllegalArgumentException("roleCode 不能为空");
		}
		if(opCodeList == null) {
			throw new IllegalArgumentException("opCodeList 不能为空");
		}
		RedisUtils.del(roleCode + "_operation");
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("tenantCode", ApplicationConfig.getAuthorityTenantCode());
		param.put("opCodeList", opCodeList);
		param.put("roleCode", roleCode);
		String url = ApplicationConfig.getAuthorityUrl() + ApplicationConfig.ADD_ROLE_OPERATE_URL;
		String result = HttpUtils.sendPostJson(url, JsonUtils.objectToJson(param));
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("添加角色操作失败");
		}
	}
	
	public List<OperateBean> getUserOPList(String _userCode) {
		if(StringUtils.isEmpty(_userCode)) {
			throw new IllegalArgumentException("roleCode 不能为空");
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("tenantCode", ApplicationConfig.getAuthorityTenantCode());
		param.put("userCode", _userCode);
		String url = ApplicationConfig.getAuthorityUrl() + ApplicationConfig.GET_USER_OPT_LIST;
		String result = HttpUtils.sendPostJson(url, JsonUtils.objectToJson(param));
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("删除操作失败");
		}
		return JsonUtils.jsonToList(json.getString("data"), OperateBean.class);
	}
	
	public void deleteRoleOP(String roleCode, List<String> opCodeList) {
		if(StringUtils.isEmpty(roleCode)) {
			throw new IllegalArgumentException("roleCode 不能为空");
		}
		if(opCodeList == null) {
			throw new IllegalArgumentException("opCodeList 不能为空");
		}
		RedisUtils.del(roleCode + "_operation");
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("tenantCode", ApplicationConfig.getAuthorityTenantCode());
		param.put("roleCode", roleCode);
		param.put("opCodeList", opCodeList);
		String url = ApplicationConfig.getAuthorityUrl() + ApplicationConfig.DELETE_ROLE_OPERATE;
		String result = HttpUtils.sendPostJson(url, JsonUtils.objectToJson(param));
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("删除角色操作失败");
		}
	}
	
	public PageInfo<OperationTreeBean> listAllOperation(OperationQueryBean query) {
		if(StringUtils.isEmpty(query.getApp())) {
			throw new IllegalArgumentException("app 不能为空");
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("tenantCode", ApplicationConfig.getAuthorityTenantCode());
		param.put("app", query.getApp());
		param.put("opFlag", 1);
		param.put("page", query.getPage());
		param.put("pageSize", query.getPageCount());
		if(StringUtils.isNotEmpty(query.getOpName())) {
			param.put("opName", query.getOpName());
		}
		String url = ApplicationConfig.getAuthorityUrl() + "/permissionController/queryAllOP.htm";
		String result = HttpUtils.sendPostJson(url, JsonUtils.objectToJson(param));
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("查询角色所有操作菜单失败");
		}
		PageInfo<OperationTreeBean> page = new PageInfo<OperationTreeBean>();
		List<OperationTreeBean> data = JsonUtils.jsonToList(json.getString("data"), OperationTreeBean.class);
		page.setList(data);
		page.setPageSize(query.getPageCount());
		page.setPageNum(json.getInt("page"));
		page.setTotal(json.getLong("totalCount"));
		return page;
	}
	
	public MessageBean<?> initOperation(SessionFactory factory){
		
		return null;
	}
	
	public List<OperationTreeBean> listOPByOrg(String app, String orgCode) {
		if(StringUtils.isEmpty(app)) {
			throw new IllegalArgumentException("app 不能为空");
		}
		if(StringUtils.isEmpty(orgCode)) {
			throw new IllegalArgumentException("orgCode 不能为空");
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("tenantCode", ApplicationConfig.getAuthorityTenantCode());
		param.put("app", app);
		param.put("orgCode", orgCode);
		String url = ApplicationConfig.getAuthorityUrl() + "/permissionController/queryOPByOrg.htm";
		String result = HttpUtils.sendPostJson(url, JsonUtils.objectToJson(param));
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("查询组织操作菜单失败");
		}
		return JsonUtils.jsonToList(json.getString("data"), OperationTreeBean.class);
	}
	
	public List<OperationTreeBean> listOPByOrg(String app,UserInfoBean userInfo, String orgCode, boolean checked) {
		if(StringUtils.isEmpty(app)) {
			throw new IllegalArgumentException("app 不能为空");
		}
		if(StringUtils.isEmpty(orgCode)) {
			throw new IllegalArgumentException("orgCode 不能为空");
		}
		List<OperationTreeBean> roleOperation = listOPByOrg(app, orgCode);
		if(!checked) {
			return roleOperation;
		}
		OperationQueryBean query = new OperationQueryBean();
		query.setTenantCode(ApplicationConfig.getAuthorityTenantCode());
		query.setApp(app);
		query.setPage(1);
		query.setPageCount(Integer.MAX_VALUE);
		PageInfo<OperationTreeBean> page = listAllOperation(query);
		List<OperationTreeBean> allOperation = page.getList();
		for(OperationTreeBean operation : allOperation) {
			for(OperationTreeBean op : roleOperation) {
				if(Objects.equal(operation.getOpCode(), op.getOpCode())) {
					operation.setChecked(true);
				}
				List<OperationTreeBean> btnList = operation.getBtnList();
				if(btnList != null && btnList.size() > 0) {
					for(OperationTreeBean btn : btnList) {
						if(Objects.equal(btn.getOpCode(), op.getOpCode())) {
							btn.setChecked(true);
						}
					}
				}
			}
		}
		return allOperation;
	}
	
	public List<OperationTreeBean> listOPByRole(String app, UserInfoBean userInfo, String roleCode, boolean checked) {
		if(StringUtils.isEmpty(roleCode)) {
			throw new IllegalArgumentException("roleCode 不能为空");
		}
		List<OperationTreeBean> allOperation = null;
		List<OperationTreeBean> roleOperation = listOPByRole(app, roleCode);
		/*if(StringUtils.isNotEmpty(userInfo.getCurWaterCode())) {
			allOperation = listOPByOrg(app,userInfo.getCurWaterCode());
			Iterator<OperationTreeBean> iterator = roleOperation.iterator();
			while (iterator.hasNext()) {
				OperationTreeBean operation = iterator.next();
				if(!allOperation.contains(operation)) {
					iterator.remove();
				}
			}
		}*/
		if(!checked) {
			return roleOperation;
		}
		//String cache = RedisUtils.get("orgalloperation");
		//运维上水司编号为空获取角色所有权限（无关水司）
		if(StringUtils.isEmpty(userInfo.getCurWaterCode())){
			OperationQueryBean query = new OperationQueryBean();
			query.setTenantCode(ApplicationConfig.getAuthorityTenantCode());
			query.setApp(app);
			query.setPage(1);
			query.setPageCount(Integer.MAX_VALUE);
			PageInfo<OperationTreeBean> page = listAllOperation(query);
			allOperation = page.getList();
		}
		
		//if(StringUtils.isNotBlank(cache)) {
		//	allOperation = JsonUtils.jsonToList(cache, OperationTreeBean.class);
		//} else {
			//allOperation = listOPByOrg(app,userInfo.getCurWaterCode());
			/*OperationQueryBean query = new OperationQueryBean();
			query.setTenantCode(ApplicationConfig.getAuthorityTenantCode());
			query.setApp(app);
			query.setPage(1);
			query.setPageCount(Integer.MAX_VALUE);
			PageInfo<OperationTreeBean> page = listAllOperation(query);
			allOperation = page.getList();*/
			//RedisUtils.setEx("orgalloperation", ApplicationConfig.getExpireTime(), JsonUtils.objectToJson(allOperation));
		//}
		for(OperationTreeBean operation : allOperation) {
			for(OperationTreeBean op : roleOperation) {
				if(Objects.equal(operation.getOpCode(), op.getOpCode())) {
					operation.setChecked(true);
				}
				List<OperationTreeBean> btnList = operation.getBtnList();
				if(btnList != null && btnList.size() > 0) {
					for(OperationTreeBean btn : btnList) {
						if(Objects.equal(btn.getOpCode(), op.getOpCode())) {
							btn.setChecked(true);
						}
					}
				}
			}
		}
		return allOperation;
	}
	
	public List<OperationTreeBean> listOPByRole(String app, String roleCode) {
		if(StringUtils.isEmpty(roleCode)) {
			throw new IllegalArgumentException("roleCode 不能为空");
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("tenantCode", ApplicationConfig.getAuthorityTenantCode());
		param.put("roleCode", roleCode);
		String url = ApplicationConfig.getAuthorityUrl() + "/permissionController/queryOPByRole.htm";
		String result = HttpUtils.sendPostJson(url, JsonUtils.objectToJson(param));
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("查询角色所有操作菜单失败");
		}
		return JsonUtils.jsonToList(json.getString("data"), OperationTreeBean.class);
	} 
	
}
